package com.colorful.insuranceproject.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.NetWorkImageHolderView;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.colorful.insuranceproject.R;
import com.colorful.insuranceproject.adapter.GridImgsAdapter;
import com.colorful.insuranceproject.adapter.HomeHealthInfoAdapter;
import com.colorful.insuranceproject.adapter.MicroDrugListAdapter;
import com.colorful.insuranceproject.base.PLEFragment;
import com.colorful.insuranceproject.base.WebViewActivity;
import com.colorful.insuranceproject.bean.HealthInfoBean;
import com.colorful.insuranceproject.bean.HomeBean;
import com.colorful.insuranceproject.bean.MicroDrugListBean;
import com.colorful.insuranceproject.bean.PersonInfoBean;
import com.colorful.insuranceproject.claims.ClaimsTypeActivity;
import com.colorful.insuranceproject.claims.UploadRecordActivity;
import com.colorful.insuranceproject.commonActivity.MainActivity;
import com.colorful.insuranceproject.consts.CodeTable;
import com.colorful.insuranceproject.consts.URLConst;
import com.colorful.insuranceproject.home.ConsultDetailsActivity;
import com.colorful.insuranceproject.home.MessageActivity;
import com.colorful.insuranceproject.home.ColorfulActivity;
import com.colorful.insuranceproject.mine.PaymentCodeActivity;
import com.colorful.insuranceproject.mine.QuotaInfoActivity;
import com.colorful.insuranceproject.request.HomeRequest;
import com.colorful.insuranceproject.request.MineRequest;
import com.colorful.insuranceproject.utils.getSigin;
import com.lovely3x.common.activities.refresh.CanLoadMore;
import com.lovely3x.common.managements.user.UserManager;
import com.lovely3x.common.utils.ALog;
import com.lovely3x.common.utils.Response;
import com.lovely3x.common.utils.ViewUtils;
import com.lovely3x.common.widgets.EnoughHeightGridView;
import com.lovely3x.loginandresgiter.bean.SimpleUser;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by handsome-Bob on 2017/10/27.
 * <p>
 * 主页的Fragment
 */
public class HomeFragment extends PLEFragment implements AdapterView.OnItemClickListener,
        OnItemClickListener, GridImgsAdapter.ImageClickedListener, CanLoadMore, View.OnClickListener {

    private static final int GET_HOME_PAGE_URL = 0X1;

    private static final int GET_MINE_FRAGMENT_PAGE_DATA = 0X2;

    HomeRequest homeRequest;

    MineRequest mineRequest;

    /**
     * 操作栏适配器
     */
    private MicroDrugListAdapter microDrugListAdapter;

    /**
     * 健康资讯的列表
     */
    private HomeHealthInfoAdapter homeHealthInfoAdapter;

    /**
     * 操作栏
     */
    EnoughHeightGridView enoughHeightGridView;

    /**
     * Banner
     */
    ConvenientBanner banner;

    /**
     * 首页列表
     */
    @Bind(R.id.ehlv_home)
    ListView list_home;

    @Bind(R.id.fl_fragment_list_empty_container)
    ViewGroup viewContainer;

    List<String> mBannerUrls;

    private TextView modifyDrug;

    private PersonInfoBean pb;

    SimpleUser simpleUser;

    @Override
    protected int getContentView() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this, mRootView);
    }

    @Override
    protected void onViewInitialized() {

        mBannerUrls = new ArrayList<>();
        View headView = getLayoutInflater().inflate(R.layout.view_home_head, list_home, false);
        enoughHeightGridView = (EnoughHeightGridView) headView.findViewById(R.id.ehgv_home_nav);
        banner = (ConvenientBanner) headView.findViewById(R.id.cb_banner);
        headView.findViewById(R.id.tv_code_direct).setOnClickListener(this);
        headView.findViewById(R.id.tv_web_drug).setOnClickListener(this);
        headView.findViewById(R.id.tv_web_shop).setOnClickListener(this);
        modifyDrug = (TextView) headView.findViewById(R.id.tv_web_drug);
        list_home.addHeaderView(headView);

        homeRequest = new HomeRequest(getHandler());
        mineRequest = new MineRequest(getHandler());
        microDrugListAdapter = new MicroDrugListAdapter(makeMethodList(), mActivity);
        enoughHeightGridView.setAdapter(microDrugListAdapter);
        enoughHeightGridView.setOnItemClickListener(this);

        homeHealthInfoAdapter = new HomeHealthInfoAdapter(null, mActivity);
        homeHealthInfoAdapter.setOnImgViewClickedListener(this);
        list_home.setAdapter(homeHealthInfoAdapter);
        list_home.setOnItemClickListener(this);
        initBanner();

        /*
         *   获取首页数据
         */
        onContentStatusChanged(LOADING_CONTENT);
        currentIndex = DEFAULT_POST_FIRST_PAGE;
        getData();

        String mm = getSigin.getApkSignInfo("../app/build/outputs/apk/app-debug.apk");
        ALog.e(TAG, "查看当前日志---------------->" + mm);
    }

    private void getData() {
        if (homeRequest != null) {
            homeRequest.getHomePageData(currentIndex, GET_HOME_PAGE_URL);
        }
    }

    @Override
    public void onBeginRefresh() {
        //ignore
    }

    @Override
    public void onBeginLoadMore() {
        currentIndex++;
        getData();
    }

    /**
     * 初始化banner
     */
    private void initBanner() {
        // 设置记录的小标点
        banner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT);
        banner.setPageIndicator(new int[]{R.drawable.banner_page_indicator_ponit_uncheck, R.drawable.banner_page_indicator_point_checked});
        banner.setOnItemClickListener(this);
        banner.startTurning(5000);//5秒一翻页
        banner.setCanLoop(true);//无限循环

        ViewGroup.LayoutParams params = banner.getLayoutParams();
        params.width = ViewUtils.getWidth();
        params.height = (int) (params.width * (6 * 1.0f / 25));
        banner.setLayoutParams(params);
    }

    /**
     * 创建支付方式列表
     */
    protected List<MicroDrugListBean> makeMethodList() {
        ArrayList<MicroDrugListBean> methods = new ArrayList<>();
        methods.add(new MicroDrugListBean(1, getString(R.string.claim_upload), R.drawable.icon_lipeiishangchuan));
        methods.add(new MicroDrugListBean(2, getString(R.string.history_upload), R.drawable.icon_lishishangchuan));
//        methods.add(new MicroDrugListBean(3, getString(R.string.Schedule_query), R.drawable.icon_jinduchaxun));
        methods.add(new MicroDrugListBean(4, getString(R.string.account_limit), R.drawable.icon_zhanghuedu));
//        methods.add(new MicroDrugListBean(5, getString(R.string.used_manual), R.drawable.icon_shiyongshouce));
        methods.add(new MicroDrugListBean(6, getString(R.string.more_server), R.drawable.icon_gengduofuwu));
        return methods;
    }

    @Override
    protected void handleResponseMessage(Message msg, Response response) {
        super.handleResponseMessage(msg, response);
        switch (msg.what) {
            case GET_HOME_PAGE_URL:
                handleRefreshState(response, homeHealthInfoAdapter);
                if (response.isSuccessful) {
                    HomeBean bean = (HomeBean) response.obj;
                    mBannerUrls = bean.getBanners();
                    if (mBannerUrls.size() <= 1) {
                        banner.setCanLoop(false);//无限循环
                        banner.setPointViewVisible(false);
                    }

                    banner.setPages(new CBViewHolderCreator<Holder<String>>() {
                        @Override
                        public Holder<String> createHolder() {
                            return new NetWorkImageHolderView();
                        }
                    }, mBannerUrls);

                    onContentStatusChanged(LOADING_SUCCESSFUL);
                    if (currentIndex == 0 && bean.getArticles().size() == 0) {
                        onContentStatusChanged(LOADING_FAILURE, getString(R.string.not_find_data), this);
                    } else {
                        setListPageData(bean.getArticles(), response.addtional);
                    }
                } else {
                    if (response.addtional == DEFAULT_POST_FIRST_PAGE) {
                        onContentStatusChanged(LOADING_FAILURE, CodeTable.getInstance().getCodeDescription(response), this);
                    }
                }
                break;

            case GET_MINE_FRAGMENT_PAGE_DATA:
                if (response.isSuccessful) {
                    pb = (PersonInfoBean) response.obj;
                } else {
                    mActivity.showToast(CodeTable.getInstance().getCodeDescription(response));
                }
                break;
        }
    }

    private void setListPageData(List<HealthInfoBean> listData, int addtional) {
        switch (addtional) {
            case DEFAULT_POST_FIRST_PAGE:
                homeHealthInfoAdapter.setData(listData);
                break;
            default:
                homeHealthInfoAdapter.addDataToLast(listData);
                break;
        }
    }

    @Override
    protected void restoreInstanceOnCreateBefore(Bundle savedInstanceState) {

    }

    @Override
    protected void restoreInstanceOnCreateAfter(Bundle savedInstanceState) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getAdapter() == microDrugListAdapter) {
            MicroDrugListBean bean = (MicroDrugListBean) parent.getAdapter().getItem(position);
            switch (bean.getId()) {
                case 1://理赔上传
                    mActivity.launchActivityNeedLogin(ClaimsTypeActivity.class);
                    break;
                case 2://理赔记录
                    mActivity.launchActivityNeedLogin(UploadRecordActivity.class);
                    break;
                case 3://进度查询
//                    mActivity.launchActivityNeedLogin(ClaimsProgressActivity.class);
                    break;
                case 4://账户额度
                    if (pb != null)
                        mActivity.launchActivityNeedLogin(QuotaInfoActivity.class, QuotaInfoActivity.EXTRA_QUOTA_INFO, pb.getMoneyInfo());
                    break;
                case 5://使用手册
                    mActivity.showToast(getString(R.string.function_development));
                    break;
                case 6://更多服务
                    ((MainActivity) getActivity()).setCurrentTab(1);
                    break;

            }
        } else {
            HealthInfoBean healthInfoBean = (HealthInfoBean) parent.getAdapter().getItem(position);
            mActivity.launchActivity(ConsultDetailsActivity.class, ConsultDetailsActivity.EXTRA_DETAILS, healthInfoBean);
        }
    }

    @Override
    public void onItemClick(int position) {
        mActivity.showHTTPURLImgOnNewActivity(mBannerUrls, position);
    }

    @OnClick({R.id.img_guest_service, R.id.img_message})
    void OnClicked(View view) {
        switch (view.getId()) {
            // 客服
            case R.id.img_guest_service:
                final String number = URLConst.CUSTOMER_SERVICE_TELEPHONE_NUMBERS;
                mActivity.showConfirmDialog(getString(R.string.contact_customer_service), number, null, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + getString(R.string.call_constomer_server)));
                        startActivity(intent);
                    }
                }).show();
                break;
            // 消息
            case R.id.img_message:
                mActivity.launchActivity(MessageActivity.class);
                break;
        }
    }

    @Override
    public void onImageClicked(int parentPosition, int position, View view) {
        HealthInfoBean healthInfoBean = homeHealthInfoAdapter.getItem(parentPosition);
        mActivity.launchActivity(ConsultDetailsActivity.class, ConsultDetailsActivity.EXTRA_DETAILS, healthInfoBean);
    }

    @Override
    protected ViewGroup getEmptyContainerView() {
        return viewContainer;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //扫码直赔
            case R.id.tv_code_direct:
                mActivity.launchActivityNeedLogin(PaymentCodeActivity.class);
                break;
            //线上购药  九州
            case R.id.tv_web_drug:
                if (simpleUser.getUserPhone().equals("18557545114")) {
                    ((MainActivity) getActivity()).setCurrentTab(2);
                } else {
                    mActivity.launchActivityNeedLogin(WebViewActivity.class, WebViewActivity.EXTRA_ID, 2);
                }
                break;
            //精美购物 可乐否
            case R.id.tv_web_shop:
                mActivity.launchActivityNeedLogin(ColorfulActivity.class);
                break;
            default:
                onContentStatusChanged(LOADING_CONTENT);
                currentIndex = DEFAULT_POST_FIRST_PAGE;
                getData();
                break;
        }
    }

    @Override
    public void onUserHintVisibleChanged(boolean isVisibleToUser, boolean isFirstVisible) {
        super.onUserHintVisibleChanged(isVisibleToUser, isFirstVisible);
        if (isVisibleToUser) {
            simpleUser = (SimpleUser) UserManager.getInstance().getCurrentUser();
            if (simpleUser.getUserPhone().equals("18557545114")) {
                modifyDrug.setText("健康资讯");
                Drawable draw = ContextCompat.getDrawable(mActivity, R.drawable.icon_jiankang);
                modifyDrug.setCompoundDrawablesWithIntrinsicBounds(null, draw, null, null);
            } else {
                modifyDrug.setText(getString(R.string.web_drug));
                Drawable draw = ContextCompat.getDrawable(mActivity, R.drawable.icon_xianshanggouyao);
                modifyDrug.setCompoundDrawablesWithIntrinsicBounds(null, draw, null, null);
            }

            if (!UserManager.getInstance().isSigned()) {
                mActivity.launchLoginActivity();
            } else {
                mineRequest.getUserInfoUrl(GET_MINE_FRAGMENT_PAGE_DATA);
            }
        }
    }
}
